import React, { useState, useEffect } from 'react';
import { 
  Layout, 
  Typography, 
  Card, 
  Table, 
  Button, 
  Breadcrumb, 
  Space,
  Tag,
  List,
  Avatar,
  Row,
  Col,
  Spin,
  Result
} from 'antd';
import { 
  DownloadOutlined, 
  HomeOutlined,
  FolderOutlined,
  FileOutlined,
  EyeOutlined,
  ShareAltOutlined,
  LockOutlined
} from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom';

const { Title, Text } = Typography;

// Mock数据：完整的目录结构
const mockDirectoryStructure = {
  id: 'root',
  name: '资源目录',
  type: 'folder',
  children: [
    {
      id: '1',
      name: '文档资料',
      type: 'folder',
      size: '-',
      modified: '2023-06-15',
      children: [
        {
          id: '11',
          name: '项目需求文档.docx',
          type: 'file',
          size: '2.4 MB',
          modified: '2023-06-10',
          fileType: 'document'
        },
        {
          id: '12',
          name: '技术规范.pdf',
          type: 'file',
          size: '5.1 MB',
          modified: '2023-06-12',
          fileType: 'pdf'
        }
      ]
    },
    {
      id: '2',
      name: '设计素材',
      type: 'folder',
      size: '-',
      modified: '2023-06-18',
      children: [
        {
          id: '21',
          name: 'Logo设计',
          type: 'folder',
          size: '-',
          modified: '2023-06-15',
          children: [
            {
              id: '211',
              name: 'logo.png',
              type: 'file',
              size: '1.2 MB',
              modified: '2023-06-15',
              fileType: 'image'
            },
            {
              id: '212',
              name: 'logo.svg',
              type: 'file',
              size: '0.8 MB',
              modified: '2023-06-15',
              fileType: 'image'
            }
          ]
        },
        {
          id: '22',
          name: '宣传海报.psd',
          type: 'file',
          size: '15.3 MB',
          modified: '2023-06-18',
          fileType: 'image'
        }
      ]
    },
    {
      id: '3',
      name: '视频资源',
      type: 'folder',
      size: '-',
      modified: '2023-06-20',
      children: [
        {
          id: '31',
          name: '产品介绍视频.mp4',
          type: 'file',
          size: '124.5 MB',
          modified: '2023-06-19',
          fileType: 'video'
        },
        {
          id: '32',
          name: '使用教程.avi',
          type: 'file',
          size: '87.2 MB',
          modified: '2023-06-20',
          fileType: 'video'
        }
      ]
    },
    {
      id: '4',
      name: '安装包.exe',
      type: 'file',
      size: '45.7 MB',
      modified: '2023-06-22',
      fileType: 'application'
    },
    {
      id: '5',
      name: '用户手册.txt',
      type: 'file',
      size: '0.3 MB',
      modified: '2023-06-21',
      fileType: 'document'
    }
  ]
};

const Resource = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [currentPath, setCurrentPath] = useState([{ id: 'root', name: '资源目录' }]);
  const [directoryStructure, setDirectoryStructure] = useState(null);
  const [currentFiles, setCurrentFiles] = useState([]);
  const [isMobile, setIsMobile] = useState(window.innerWidth <= 768);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 监听窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth <= 768);
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 组件挂载时检查secret参数并请求数据
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    const secret = searchParams.get('secret');
    
    // 如果没有secret参数，重定向到首页
    if (!secret) {
      navigate('/');
      return;
    }

    // 模拟请求后端数据
    simulateBackendRequest(secret);
  }, []);

  // 初始化和路径变化时更新当前文件列表
  useEffect(() => {
    updateCurrentFiles();
  }, [currentPath, directoryStructure]);

  // 模拟向后端请求文件列表数据
  const simulateBackendRequest = (secret) => {
    setLoading(true);
    setError(null);
    
    // 模拟网络请求延迟
    setTimeout(() => {
      // 模拟验证逻辑：只有当secret为"valid-secret"时才认为是有效的
      if (secret === 'valid-secret') {
        setDirectoryStructure(mockDirectoryStructure);
      } else {
        setError('密钥无效，请检查您的密钥是否正确');
      }
      setLoading(false);
    }, 1500);
  };

  // 更新当前目录下的文件列表
  const updateCurrentFiles = () => {
    if (!directoryStructure) return;
    
    if (currentPath.length === 1) {
      setCurrentFiles(directoryStructure.children || []);
      return;
    }

    let current = directoryStructure.children || [];
    for (let i = 1; i < currentPath.length; i++) {
      const folder = current.find(item => item.id === currentPath[i].id);
      if (folder && folder.children) {
        current = folder.children;
      } else {
        current = [];
        break;
      }
    }
    setCurrentFiles(current);
  };

  // 进入文件夹
  const enterFolder = (folder) => {
    setCurrentPath([...currentPath, { id: folder.id, name: folder.name }]);
  };

  // 返回上一级
  const goBack = () => {
    if (currentPath.length > 1) {
      const newPath = [...currentPath];
      newPath.pop();
      setCurrentPath(newPath);
    }
  };

  // 返回根目录
  const goHome = () => {
    setCurrentPath([{ id: 'root', name: '资源目录' }]);
  };

  // 下载文件
  const downloadFile = (file) => {
    // 实际项目中这里会触发文件下载
  };

  // 预览文件
  const previewFile = (file) => {
    // 实际项目中这里会打开文件预览
  };

  // 分享文件
  const shareFile = (file) => {
    // 实际项目中这里会打开分享功能
  };

  // 文件类型标签颜色
  const getFileTypeColor = (fileType) => {
    switch (fileType) {
      case 'document': return 'blue';
      case 'pdf': return 'red';
      case 'image': return 'green';
      case 'video': return 'orange';
      case 'application': return 'purple';
      default: return 'default';
    }
  };

  // 获取文件图标
  const getFileIcon = (item) => {
    if (item.type === 'folder') {
      return <FolderOutlined style={{ fontSize: '24px', color: '#FFCC00' }} />;
    }
    
    switch (item.fileType) {
      case 'image':
        return <FileOutlined style={{ fontSize: '24px', color: '#4CAF50' }} />;
      case 'pdf':
        return <FileOutlined style={{ fontSize: '24px', color: '#F44336' }} />;
      case 'video':
        return <FileOutlined style={{ fontSize: '24px', color: '#2196F3' }} />;
      case 'document':
        return <FileOutlined style={{ fontSize: '24px', color: '#9C27B0' }} />;
      default:
        return <FileOutlined style={{ fontSize: '24px', color: '#607D8B' }} />;
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          {record.type === 'folder' ? (
            <FolderOutlined style={{ color: '#FFCC00', fontSize: '18px' }} />
          ) : (
            <FileOutlined style={{ color: '#1890ff', fontSize: '18px' }} />
          )}
          {record.type === 'folder' ? (
            <Button 
              type="link" 
              onClick={() => enterFolder(record)}
              style={{ padding: 0, height: 'auto' }}
            >
              {text}
            </Button>
          ) : (
            <span>{text}</span>
          )}
          {record.type === 'file' && (
            <Tag color={getFileTypeColor(record.fileType)}>
              {record.fileType}
            </Tag>
          )}
        </Space>
      )
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      width: 120
    },
    {
      title: '修改日期',
      dataIndex: 'modified',
      key: 'modified',
      width: 150
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        record.type === 'file' ? (
          <Space>
            <Button 
              type="primary" 
              icon={<DownloadOutlined />}
              size="small"
              onClick={() => downloadFile(record)}
              style={{ 
                borderRadius: '4px',
                background: 'linear-gradient(45deg, #1890ff, #40a9ff)',
                border: 'none'
              }}
            >
              下载
            </Button>
            <Button 
              icon={<EyeOutlined />}
              size="small"
              onClick={() => previewFile(record)}
              style={{ 
                borderRadius: '4px'
              }}
            >
              预览
            </Button>
            <Button 
              icon={<ShareAltOutlined />}
              size="small"
              onClick={() => shareFile(record)}
              style={{ 
                borderRadius: '4px'
              }}
            >
              分享
            </Button>
          </Space>
        ) : null
      )
    }
  ];

  // 如果仍在加载中，显示解锁中的卡片
  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: 'calc(100vh - 64px)',
        padding: '20px'
      }}>
        <Card style={{ 
          width: '100%',
          maxWidth: '400px',
          backgroundColor: 'rgba(255, 255, 255, 0.05)',
          backdropFilter: 'blur(10px)',
          borderRadius: '10px',
          textAlign: 'center'
        }} bordered={false}>
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            <LockOutlined style={{ fontSize: '48px', color: '#1890ff' }} />
            <Title level={3} style={{ color: '#fff', margin: 0 }}>
              资源解锁中
            </Title>
            <Spin size="large" />
            <Text style={{ color: 'rgba(255, 255, 255, 0.7)' }}>
              正在验证您的密钥，请稍候...
            </Text>
          </Space>
        </Card>
      </div>
    );
  }

  // 如果有错误，显示错误卡片
  if (error) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: 'calc(100vh - 64px)',
        padding: '20px'
      }}>
        <Card style={{ 
          width: '100%',
          maxWidth: '400px',
          backgroundColor: 'rgba(255, 255, 255, 0.05)',
          backdropFilter: 'blur(10px)',
          borderRadius: '10px'
        }} bordered={false}>
          <Result
            status="error"
            title="资源解锁失败"
            subTitle={error}
            extra={[
              <Button 
                type="primary" 
                key="back" 
                onClick={() => navigate('/')}
                style={{
                  background: 'linear-gradient(45deg, #1890ff, #40a9ff)',
                  border: 'none',
                  borderRadius: '6px'
                }}
              >
                返回首页
              </Button>
            ]}
          />
        </Card>
      </div>
    );
  }

  // 如果没有目录结构数据，不渲染文件列表
  if (!directoryStructure) {
    return null;
  }

  return (
    <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        {/* 页面标题 */}
        <div>
          <Title level={2} style={{ color: '#fff', marginBottom: '8px' }}>
            资源目录
          </Title>
          <Text style={{ color: 'rgba(255, 255, 255, 0.7)' }}>
            浏览和管理您的文件资源
          </Text>
        </div>

        {/* 面包屑导航 */}
        <Card style={{ 
          backgroundColor: 'rgba(255, 255, 255, 0.05)',
          backdropFilter: 'blur(10px)',
          borderRadius: '10px'
        }} bordered={false}>
          <Space style={{ width: '100%', justifyContent: 'space-between' }}>
            <Breadcrumb>
              {currentPath.map((path, index) => (
                <Breadcrumb.Item key={path.id}>
                  {index === 0 ? (
                    <Button 
                      type="link" 
                      onClick={goHome}
                      style={{ color: '#1890ff', padding: 0, height: 'auto' }}
                    >
                      <HomeOutlined /> {path.name}
                    </Button>
                  ) : (
                    <Button 
                      type="link" 
                      onClick={index === currentPath.length - 1 ? undefined : () => {
                        const newPath = currentPath.slice(0, index + 1);
                        setCurrentPath(newPath);
                      }}
                      style={{ 
                        color: index === currentPath.length - 1 ? '#fff' : '#1890ff', 
                        padding: 0, 
                        height: 'auto',
                        fontWeight: index === currentPath.length - 1 ? 'bold' : 'normal'
                      }}
                    >
                      {path.name}
                    </Button>
                  )}
                </Breadcrumb.Item>
              ))}
            </Breadcrumb>
            <Button 
              onClick={goBack}
              disabled={currentPath.length <= 1}
              style={{ 
                borderRadius: '6px',
                background: 'rgba(24, 144, 255, 0.1)',
                borderColor: 'rgba(24, 144, 255, 0.3)',
                color: '#1890ff'
              }}
            >
              返回上一级
            </Button>
          </Space>
        </Card>

        {/* 文件列表 */}
        {isMobile ? (
          // 移动端卡片式布局
          <List
            grid={{ 
              gutter: 16, 
              xs: 1,
              sm: 1,
              md: 1
            }}
            dataSource={currentFiles}
            renderItem={item => (
              <List.Item>
                <Card 
                  style={{ 
                    backgroundColor: 'rgba(255, 255, 255, 0.05)',
                    backdropFilter: 'blur(10px)',
                    borderRadius: '10px',
                    cursor: item.type === 'folder' ? 'pointer' : 'default'
                  }} 
                  bordered={false}
                  onClick={item.type === 'folder' ? () => enterFolder(item) : undefined}
                >
                  <div style={{ width: '100%' }}>
                    <Row gutter={16} align="middle">
                      <Col span={4}>
                        <div style={{ 
                          display: 'flex', 
                          justifyContent: 'center', 
                          alignItems: 'center',
                          height: '100%',
                          flexDirection: 'column'
                        }}>
                          {getFileIcon(item)}
                          <Text style={{ 
                            color: 'rgba(255, 255, 255, 0.7)', 
                            fontSize: '12px',
                            marginTop: '4px',
                            textAlign: 'center'
                          }}>
                            {item.type === 'folder' ? `${item.children ? item.children.length : 0} 项` : item.size}
                          </Text>
                        </div>
                      </Col>
                      <Col span={20}>
                        <div style={{ marginBottom: '8px', textAlign: 'left' }}>
                          <Text strong style={{ color: '#fff', fontSize: '16px' }}>
                            {item.name}
                          </Text>
                        </div>
                        <div style={{ textAlign: 'left' }}>
                          <Text style={{ color: 'rgba(255, 255, 255, 0.5)', fontSize: '12px' }}>
                            修改时间: {item.modified}
                          </Text>
                        </div>
                        
                        {item.type === 'file' && (
                          <div style={{ 
                            display: 'flex', 
                            justifyContent: 'flex-start', 
                            gap: '8px', 
                            marginTop: '16px' 
                          }}>
                            <Button 
                              type="primary" 
                              icon={<DownloadOutlined />}
                              size="small"
                              onClick={(e) => {
                                e.stopPropagation();
                                downloadFile(item);
                              }}
                              style={{ 
                                borderRadius: '4px',
                                background: 'linear-gradient(45deg, #1890ff, #40a9ff)',
                                border: 'none'
                              }}
                            >
                              下载
                            </Button>
                            <Button 
                              icon={<EyeOutlined />}
                              size="small"
                              onClick={(e) => {
                                e.stopPropagation();
                                previewFile(item);
                              }}
                              style={{ 
                                borderRadius: '4px'
                              }}
                            >
                              预览
                            </Button>
                            <Button 
                              icon={<ShareAltOutlined />}
                              size="small"
                              onClick={(e) => {
                                e.stopPropagation();
                                shareFile(item);
                              }}
                              style={{ 
                                borderRadius: '4px'
                              }}
                            >
                              分享
                            </Button>
                          </div>
                        )}
                      </Col>
                    </Row>
                  </div>
                </Card>
              </List.Item>
            )}
          />
        ) : (
          // 桌面端表格布局
          <Card style={{ 
            backgroundColor: 'rgba(255, 255, 255, 0.05)',
            backdropFilter: 'blur(10px)',
            borderRadius: '10px'
          }} bordered={false}>
            <Table
              columns={columns}
              dataSource={currentFiles}
              pagination={false}
              rowKey="id"
              locale={{
                emptyText: '该目录下暂无文件'
              }}
              style={{ 
                backgroundColor: 'transparent',
                color: '#fff'
              }}
            />
          </Card>
        )}
      </Space>
    </div>
  );
};

export default Resource;